/********* alipay.m Cordova Plugin Implementation *******/

#import "alipay.h"

@implementation alipay

#pragma mark "API"
- (void)pluginInitialize {
    CDVViewController *viewController = (CDVViewController *)self.viewController;
    NSString* appId  = [viewController.settings objectForKey:@"alipayid"];
    if (appId && ![appId isEqualToString:self.alipayAppId]) {
        self.alipayAppId = appId;
        NSLog(@"cordova-plugin-alipay has been initialized.  APP_ID: %@.", appId);
    }
}

- (void)payment:(CDVInvokedUrlCommand*)command
{
    self.currentCallbackId = command.callbackId;
    NSString* orderString = [command.arguments objectAtIndex:0];
    NSString* appScheme = [NSString stringWithFormat:@"ali%@", self.alipayAppId];
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        CDVPluginResult* pluginResult;
        
        if ([[resultDic objectForKey:@"resultStatus"]  isEqual: @"9000"]) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:resultDic];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:self.currentCallbackId];
        } else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:resultDic];
            [self.commandDelegate sendPluginResult:pluginResult callbackId:self.currentCallbackId];
        }
        
    }];
}


- (BOOL)handleAlipayOpenURL:(NSURL *)url  {
     if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            [self onPayResultReceived:resultDic];
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            [self onPayResultReceived:resultDic];
        }];
    }
   return true;
}

-(void)onPayResultReceived:(NSDictionary*)resultDic{
       CDVPluginResult* pluginResult;
         if ([[resultDic objectForKey:@"resultStatus"] isEqual: @"9000"]) {
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:resultDic];
                [self.commandDelegate sendPluginResult:pluginResult callbackId:self.currentCallbackId];
            } else {
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:resultDic];
                [self.commandDelegate sendPluginResult:pluginResult callbackId:self.currentCallbackId];
            }
}

@end
